#include "qt_sdl_tst.h"
#include <SDL.h>
#include <iostream>
#include <QtWidgets/QWidget>
#include "QLabel"
#include "QDebug"
#include <QMessageBox>
#include <QPainter>
#include <QFileDialog>
#include <QMenuBar>
SDL_Window* sdl_win = nullptr;
SDL_Renderer* sdl_ren = nullptr;
SDL_Texture* sdl_tex = nullptr;
unsigned char* sdl_buf;
int bytes_per_pixel=4;
size_t sdl_w, sdl_h;
qt_sdl_tst::qt_sdl_tst()
   
{
    int r = 0;
    label1 = new QLabel(this);
    createActions();
    createMenus();
    QString filename = QString("C:\\Users\\122\\Pictures\\qwww.bmp");
   /* image1.load(filename);
    if (image1.isNull()) {
        QMessageBox::warning(this,"Open file err","File Not found:"+filename);
        return;
    }*/
    r = SDL_Init(SDL_INIT_VIDEO);
    if (r < 0) {
        qDebug() << SDL_GetError() << "\n";
        return ;
    }
    if (!sdl_win) {
        sdl_win = SDL_CreateWindowFrom((const void*)(label1->winId()));
        if (!sdl_win) {
            qDebug() << SDL_GetError() << "\n";
            return;
        }
    }

    if (!sdl_ren) {
        sdl_ren = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
        if (sdl_ren == nullptr) {
            qDebug() << SDL_GetError();
            return;
        }
    }
}

void qt_sdl_tst::timerEvent(QTimerEvent* event)
{
    draw_pic();
    //qDebug() << "qt_sdl_tst::timerEvent";
    //size_t pos = 0;
    //static unsigned char x = 255;
    //auto addr = image1.bits();
    //for (size_t i = 0; i < sdl_h; i++)
    //{
    //    pos = i * sdl_w * bytes_per_pixel;
    //    for (size_t k = 0; k < sdl_w * bytes_per_pixel; k += bytes_per_pixel) {
    //        sdl_buf[pos + k + 0] = 0;// addr[pos + k + 0];//B
    //        sdl_buf[pos + k + 1] = 0;//addr[pos + k + 1];//G
    //        sdl_buf[pos + k + 2] = x;//addr[pos + k + 2];//R
    //        sdl_buf[pos + k + 3] = 0;//addr[pos + k + 3];//A
    //    }
    //   
    //}
    //x--;
    //SDL_UpdateTexture(sdl_tex, nullptr, sdl_buf, sdl_w * bytes_per_pixel);
    //SDL_Rect sdl_rect, render_sdl_rect;
    //sdl_rect.x = 0;
    //sdl_rect.y = 0;
    //sdl_rect.w = sdl_w;
    //sdl_rect.h = sdl_h;
    
  
}
//void qt_sdl_tst::paintEvent(QPaintEvent* e)
//{
//    QPainter p;
//    
//    //auto d = image1.bits();
//    /*int a = image1.depth();*/
//    //for (size_t i = 0; i < image1.height(); i++)
//    //{
//    //    int x = i * image1.width() * a;
//    //    for (size_t k = 0; k < image1.width() * a; k += a)
//    //    {
//    //        //85, 76, 133
//    //        //245, 241, 229
//    //        d[x + k] = 245;
//    //        d[x + k + 1] = 241;
//    //        d[x + k + 2] = 229;
//    //        d[x + k + 2] = 229;
//
//    //    }
//    //}
//    p.begin(this);
//    p.drawImage(0, 0, image1);
//    p.end();
//}

void sdl_render_image(unsigned char *addr,quint64 len, unsigned char*buffer, SDL_Renderer *ren)
{

}
void qt_sdl_tst::open()
{

    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Open File"), QDir::currentPath());
    if (!fileName.isEmpty()) {
        image1.load(fileName);
        if (!image1.isNull()) {
            QString imageinfo;
            imageinfo.append(QString("Path:%1\r\n").arg(fileName));
            imageinfo.append(QString("w:%1,h:%2\r\n").arg(image1.width()).arg(image1.height()));
            imageinfo.append(QString("hasAlphaChannel :%1\r\n").arg(image1.hasAlphaChannel() ? "Yes" : "No"));
            imageinfo.append(QString("Bit depth :%1\r\n").arg(image1.depth()));
            imageinfo.append(QString("bitsPerPixel :%1\r\n").arg(image1.pixelFormat().bitsPerPixel()));
            imageinfo.append(QString("alphaSize :%1\r\n").arg(image1.pixelFormat().alphaSize()));
            imageinfo.append(QString("AlphaPosition :%1\r\n").arg(image1.pixelFormat().alphaPosition() ? "AtEnd" : "AtBeginning"));
            imageinfo.append(QString("ByteOrder :%1\r\n").arg(image1.pixelFormat().byteOrder() ? "BigEndian" : "LittleEndian"));
            //QMessageBox::information(this, "Image info ", imageinfo);
            prepare_data();
#if 1

            startTimer(10);
#else
            isImageOpen = true;
            update();
#endif         
        }
       
    }
    else {
        
    }
}

void qt_sdl_tst::about()
//! [11] //! [12]
{
    QMessageBox::about(this, tr("About Scribble"),
        tr("<p>The <b>Scribble</b> example shows how to use QMainWindow as the "
            "base widget for an application, and how to reimplement some of "
            "QWidget's event handlers to receive the events generated for "
            "the application's widgets:</p><p> We reimplement the mouse event "
            "handlers to facilitate drawing, the paint event handler to "
            "update the application and the resize event handler to optimize "
            "the application's appearance. In addition we reimplement the "
            "close event handler to intercept the close events before "
            "terminating the application.</p><p> The example also demonstrates "
            "how to use QPainter to draw an image in real time, as well as "
            "to repaint widgets.</p>"));
}
void qt_sdl_tst::draw_pic()
{
    SDL_Rect target_rect = {0,0,label1->width(),label1->height() };
    SDL_RenderClear(sdl_ren);
    SDL_RenderCopy(sdl_ren, sdl_tex, NULL, &target_rect);
    SDL_RenderPresent(sdl_ren);



  /*  SDL_DestroyTexture(sdl_tex);
    SDL_DestroyRenderer(sdl_ren);
    SDL_DestroyWindow(sdl_win);*/

   /* sdl_buf = new  unsigned char[sdl_w * sdl_h * bytes_per_pixel];
    if (sdl_buf == nullptr) {
        qDebug() << "new error";
        return;
    }*/

}
void qt_sdl_tst::createActions()
//! [13] //! [14]
{
    openAct = new QAction(tr("&Open..."), this);
    openAct->setShortcuts(QKeySequence::Open);
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

   /* foreach(QByteArray format, QImageWriter::supportedImageFormats()) {
        QString text = tr("%1...").arg(QString(format).toUpper());

        QAction* action = new QAction(text, this);
        action->setData(format);
        connect(action, SIGNAL(triggered()), this, SLOT(save()));
        saveAsActs.append(action);
    }

    printAct = new QAction(tr("&Print..."), this);
    connect(printAct, SIGNAL(triggered()), scribbleArea, SLOT(print()));*/

    exitAct = new QAction(tr("E&xit"), this);
    exitAct->setShortcuts(QKeySequence::Quit);
    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

   /* penColorAct = new QAction(tr("&Pen Color..."), this);
    connect(penColorAct, SIGNAL(triggered()), this, SLOT(penColor()));

    penWidthAct = new QAction(tr("Pen &Width..."), this);
    connect(penWidthAct, SIGNAL(triggered()), this, SLOT(penWidth()));*/

   /* clearScreenAct = new QAction(tr("&Clear Screen"), this);
    clearScreenAct->setShortcut(tr("Ctrl+L"));
    connect(clearScreenAct, SIGNAL(triggered()),
        scribbleArea, SLOT(clearImage()));*/

    aboutAct = new QAction(tr("&About"), this);
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

    aboutQtAct = new QAction(tr("About &Qt"), this);
    connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
//! [14]

//! [15]
void qt_sdl_tst::createMenus()
//! [15] //! [16]
{
    saveAsMenu = new QMenu(tr("&Save As"), this);
    foreach(QAction * action, saveAsActs)
        saveAsMenu->addAction(action);

    fileMenu = new QMenu(tr("&File"), this);
    fileMenu->addAction(openAct);
   /* fileMenu->addMenu(saveAsMenu);
    fileMenu->addAction(printAct);*/
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);

    optionMenu = new QMenu(tr("&Options"), this);
   /* optionMenu->addAction(penColorAct);
    optionMenu->addAction(penWidthAct);
    optionMenu->addSeparator();
    optionMenu->addAction(clearScreenAct);*/

    helpMenu = new QMenu(tr("&Help"), this);
    helpMenu->addAction(aboutAct);
    helpMenu->addAction(aboutQtAct);

    menuBar()->addMenu(fileMenu);
    menuBar()->addMenu(optionMenu);
    menuBar()->addMenu(helpMenu);
}
void qt_sdl_tst::paintEvent(QPaintEvent* e)
{
    if (!image1.isNull() && isImageOpen) {
        //draw_pic();
        QPainter p;
        p.begin(this);
        p.drawImage(0, 0, image1);
        p.end();
    }
}
void qt_sdl_tst::prepare_data()
{
   
    resize(image1.width(),image1.height()+menuBar()->height());
    sdl_w = image1.width();
    sdl_h = image1.height();
    label1->move(0,menuBar()->height());
    label1->resize(sdl_w, sdl_h);
    if (sdl_tex) {
        SDL_DestroyTexture(sdl_tex);
    }
    sdl_tex = SDL_CreateTexture(sdl_ren, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, sdl_w, sdl_h);
    if (sdl_tex == nullptr) {
        qDebug() << SDL_GetError();
        return;
    }
    SDL_UpdateTexture(sdl_tex, nullptr, image1.bits(), image1.width() * 4);

}
void qt_sdl_tst::resizeEvent(QResizeEvent* e)
{  
    if (isImageOpen) {
        label1->move(0, menuBar()->height());
        label1->resize(width(),height()-menuBar()->height());
    }
    qDebug() << " resizeEvent:win"<<size()<<",menuBar().size():"<< menuBar()->size() <<",label1->size():"<< label1->size();
}